#pragma once

namespace My {

// CreateSegment

template <typename S>
CreateSegment<S>::CreateSegment(TypedSegmentSet<S> & s, SegmentType * ptr) :
	m_Segments(s), m_pSegment(ptr)
{
	assert(m_pSegment != 0);
}

template <typename S>
CreateSegment<S>::~CreateSegment()
{
	if (m_pSegment != 0)
		delete m_pSegment;
}

template <typename S>
String CreateSegment<S>::GetCaption() const
{ 
	return "Create Segment"; 
}
	
template <typename S>
bool CreateSegment<S>::Execute()
{
	assert(m_pSegment != 0);
	{
		SegmentUpdate<S> u(m_Segments);
		u.Insert(0, m_pSegment);
		m_pSegment = 0;
	}
	m_Segments.SetActiveSegment(0);
	return true;
}

template <typename S>
void CreateSegment<S>::Unexecute()
{
	assert(m_Segments.GetSegmentCount() > 0);
	{ 
		SegmentUpdate<S> u(m_Segments);
		m_pSegment = u.Erase(0);
		m_pSegment->Release();
	}
}


// DeleteSegment

template <typename S>
DeleteSegment<S>::DeleteSegment(TypedSegmentSet<S> & s, Size index) :
	m_Segments(s), m_pSegment(0), m_Index(index)
{
	assert(m_Index < m_Segments.GetSegmentCount());
}
	
template <typename S>
DeleteSegment<S>::~DeleteSegment()
{
	if (m_pSegment != 0)
		delete m_pSegment;
}

template <typename S>
String DeleteSegment<S>::GetCaption() const
{ 
	return "Delete Segment"; 
}
	
template <typename S>
bool DeleteSegment<S>::Execute()
{
	m_Active = (m_Index == m_Segments.GetActiveSegment());
	{	
		SegmentUpdate<S> u(m_Segments);
		m_pSegment = u.Erase(m_Index);
		m_pSegment->Release();
	}
	return true;
}

template <typename S>
void DeleteSegment<S>::Unexecute()
{
	assert(m_pSegment != 0);
	assert(m_Index <= m_Segments.GetSegmentCount());
	{
		SegmentUpdate<S> u(m_Segments);
		u.Insert(m_Index, m_pSegment);
	}
	if (m_Active)
		m_Segments.SetActiveSegment(int(m_Index));
	m_pSegment = 0;
}

// MoveSegment

template <typename S>
MoveSegment<S>::MoveSegment(TypedSegmentSet<S> & s, Size from, Size to) :
	m_Segments(s), m_From(from), m_To(to)
{
	assert(m_From < m_Segments.GetSegmentCount());
	assert(m_To <= m_Segments.GetSegmentCount());
	if (m_From < m_To)
		m_To--;
}

template <typename S>
MoveSegment<S>::~MoveSegment()
{
}

template <typename S>
String MoveSegment<S>::GetCaption() const
{ 
	return "Move Segment"; 
}

template <typename S>
bool MoveSegment<S>::Execute()
{
	if (m_To == m_From)
		return false;
	{
		SegmentUpdate<S> u(m_Segments);
		u.Insert(m_To, u.Erase(m_From));
	}
	return true;
}

template <typename S>
void MoveSegment<S>::Unexecute()
{
	SegmentUpdate<S> u(m_Segments);
	u.Insert(m_From, u.Erase(m_To));
}

} // My